<template>
  <div class="pc-remind-bg">
    <RemindWebSocket />
    <div class="layout-container">
      <!-- 侧边栏 -->
      <SideBar />
      <!-- 主内容区 -->
      <div class="main-content main-content-rounded">
        <div class="remind-title-row main-header">
          <el-icon class="back-btn" @click="goBack"><ArrowLeft /></el-icon>
          <span class="remind-title">提醒</span>
        </div>
        <div class="main-divider"></div>
        <!-- 时间检索区域：仅在有原始数据且非加载时显示（过滤无结果也保留） -->
        <div class="remind-search-row" v-if="!loading && hasAny">
          <div class="remind-search-box">
            <el-date-picker
              v-model="search.range"
              type="daterange"
              unlink-panels
              :default-value="[new Date(), new Date()]"
              range-separator="-"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              value-format="YYYY-MM-DD"
              clearable
              trigger="click"
              :popper-options="{ modifiers: [{ name: 'offset', options: { offset: [160, 6] } }] }"
              @keyup.enter.native="onSearch"
            />
			<div class="remind-search-btn-box">
              <el-button type="primary" class="remind-search-btn" @click="onSearch">搜索</el-button>
              <el-button class="remind-reset-btn" @click="onReset">
                <el-icon style="vertical-align: -2px; margin-right: 4px;"><RefreshLeft /></el-icon>重置
              </el-button>
			</div>
          </div>
        </div>
        
        <div class="remind-card-list" :class="{ 'is-empty': empty }" style="flex:1;min-height:0;">
          <!-- 加载/空态提示 + 列表/新增卡片 -->
          <div v-if="loading" class="loading-tip">加载中…</div>
          <template v-else>
            <!-- 完全空（后台没有任何提醒） -->
            <div v-if="!hasAny && empty" class="empty-tip">
              暂无提醒，点击
              <span class="empty-link" @click="onAddRemind">新增提醒信息</span>
              进行添加
            </div>
            <!-- 有原始数据但当前筛选无结果 -->
            <div v-else-if="hasAny && empty" class="empty-tip">
              当前并无提醒，请重置或重新选择其它时间搜索
            </div>
            <!-- 有结果：列表 + 新增卡片（栅格） -->
            <el-row v-else :gutter="24">
              <el-col v-for="(remind, idx) in reminds" :key="remind.id || idx" :span="6">
                <el-card class="remind-info-card">
                  <div class="remind-info-content-wrap">
                    <div class="remind-info-content">
                      <div class="remind-info-main">
                        <div class="remind-info-title">{{ remind.title || '-' }}</div>
                        <div class="remind-info-time">{{ formatTime(remind.time) || '' }}</div>
                      </div>
                    </div>
                    <div v-if="getRepeatLabel(remind) || remind.nextTrigger || remind.baseDate" class="remind-info-repeat-badge">
                      {{ getRepeatLabel(remind) || remind.nextTrigger || remind.baseDate }}
                    </div>
                  </div>
                  <div class="remind-info-actions">
                    <el-button class="remind-info-action-btn" link @click="onEditRemind(idx)" :title="''"><el-icon style="vertical-align: middle; margin-right: 4px;"><EditPen /></el-icon>修改</el-button>
                    <div class="remind-info-action-divider"></div>
                    <el-button class="remind-info-action-btn delete" link @click="onDeleteRemind(idx)" :title="''"><el-icon style="vertical-align: middle; margin-right: 4px;"><DeleteFilled /></el-icon>删除</el-button>
                  </div>
                </el-card>
              </el-col>
              <!-- 新增卡片（空态与非空都展示） -->
              <el-col :span="6">
                <el-card class="remind-info-card remind-info-add-card" @click="onAddRemind">
                  <div class="remind-info-add">
                    <el-icon class="remind-info-add-icon"><Plus /></el-icon>
                    <div class="remind-info-add-text">新增提醒信息</div>
                  </div>
                </el-card>
              </el-col>
            </el-row>
          </template>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue';
// 统一导航封装（跨端）
import { go } from '@/utils/nav.js';
import { ArrowLeft, Plus, EditPen, DeleteFilled, Calendar, RefreshLeft } from '@element-plus/icons-vue';
import SideBar from '/pages/pc/sideBar.vue';
import { ElDatePicker, ElForm, ElFormItem, ElButton, ElMessageBox } from 'element-plus';
import { useUserStore } from '@/store/modules/user';
import { getReminderList, getDictData, deleteReminder } from '@/api/pc/elderly';
import { useReminderEditStore } from '@/store/modules/reminder.js';
import RemindWebSocket from '@/components/RemindWebSocket.vue'; 

const userStore = useUserStore();
const reminderEditStore = useReminderEditStore();

// 列表数据（reminds 为当前显示；originalReminds 缓存全部数据用于本地筛选）
const reminds = ref([]);
const originalReminds = ref([]);
const loading = ref(false);
const empty = ref(false);
const pageNum = ref(1);
const pageSize = ref(12);
const total = ref(0);
// 是否存在任何原始数据（用于区分“无任何提醒”与“筛选为空”）
const hasAny = computed(() => originalReminds.value.length > 0);
// 重复类型字典
const repeatTypeMap = ref({});

// 时间检索（日期范围，接口传 YYYY-MM-DD）
const search = ref({ range: [] });

// 格式化时间显示，去掉秒数，只显示时分
function formatTime(timeStr) {
  if (!timeStr) return '';
  
  // 如果是时间字符串，格式化为 HH:mm
  if (typeof timeStr === 'string') {
    // 匹配 HH:mm:ss 或 HH:mm 格式
    const timeMatch = timeStr.match(/^(\d{1,2}):(\d{1,2})(?::(\d{1,2}))?$/);
    if (timeMatch) {
      const hours = timeMatch[1].padStart(2, '0');
      const minutes = timeMatch[2].padStart(2, '0');
      return `${hours}:${minutes}`;
    }
    
    // 如果是完整的日期时间字符串，提取时间部分
    const dateTimeMatch = timeStr.match(/T(\d{1,2}):(\d{1,2}):(\d{1,2})/);
    if (dateTimeMatch) {
      const hours = dateTimeMatch[1].padStart(2, '0');
      const minutes = dateTimeMatch[2].padStart(2, '0');
      return `${hours}:${minutes}`;
    }
  }
  
  // 如果是Date对象
  if (timeStr instanceof Date) {
    const hours = String(timeStr.getHours()).padStart(2, '0');
    const minutes = String(timeStr.getMinutes()).padStart(2, '0');
    return `${hours}:${minutes}`;
  }
  
  // 如果无法解析，返回原值
  return timeStr;
}

function fmtDate(val) {
  if (!val) return ''
  // 支持传入 YYYY-MM-DD 字符串
  const d = typeof val === 'string' ? new Date(val.replace(/-/g,'/')) : val
  if (isNaN(d.getTime())) return ''
  const y = d.getFullYear()
  const m = String(d.getMonth() + 1).padStart(2, '0')
  const dd = String(d.getDate()).padStart(2, '0')
  return `${y}-${m}-${dd}`
}

// 从后端分页接口拉取全部（用于本地过滤）
const fetchList = async (reset = false) => {
  if (!userStore.id) return;
  loading.value = true;
  if (reset) pageNum.value = 1;
  try {
    const all = [];
    let page = 1;
    let totalVal = 0;
    // 保护上限，避免极端情况下死循环
    const MAX_PAGES = 100;
    while (page <= MAX_PAGES) {
  const res = await getReminderList(userStore.id, page, pageSize.value);
      const rows = Array.isArray(res?.rows)
        ? res.rows
        : (Array.isArray(res?.data?.rows) ? res.data.rows : (Array.isArray(res?.data) ? res.data : []));
      const normRows = rows.filter(r => r && typeof r === 'object');
      totalVal = Number(res?.total ?? res?.data?.total ?? (totalVal || normRows.length)) || 0;
      if (!normRows.length) break;
      all.push(...normRows);
      if (totalVal && all.length >= totalVal) break;
      page++;
    }
    originalReminds.value = all;
    total.value = totalVal || all.length;
    applyFilter();
  } catch (e) {
    originalReminds.value = [];
    reminds.value = [];
    total.value = 0;
    empty.value = true;
  } finally {
    loading.value = false;
  }
};

// 取提醒的用于比较的日期（优先级：baseDate > nextTrigger > createAt > createTime > updatedAt > updateAt）
function extractDateStr(remind) {
  const raw = remind?.baseDate || remind?.nextTrigger || remind?.createAt || remind?.createTime || remind?.updatedAt || remind?.updateAt;
  if (!raw) return null;
  // 如果是纯日期
  if (/^\d{4}-\d{2}-\d{2}$/.test(raw)) return raw;
  const d = new Date(raw);
  if (isNaN(d.getTime())) return null;
  const y = d.getFullYear();
  const m = String(d.getMonth() + 1).padStart(2, '0');
  const dd = String(d.getDate()).padStart(2, '0');
  return `${y}-${m}-${dd}`;
}

// 本地应用筛选
function applyFilter() {
  const [rs, re] = Array.isArray(search.value.range) ? search.value.range : [];
  if (!rs || !re) {
    reminds.value = [...originalReminds.value];
    empty.value = reminds.value.length === 0;
    return;
  }
  const start = new Date(`${rs}T00:00:00`);
  const end = new Date(`${re}T23:59:59`);
  if (isNaN(start.getTime()) || isNaN(end.getTime())) {
    reminds.value = [...originalReminds.value];
    empty.value = reminds.value.length === 0;
    return;
  }
  reminds.value = originalReminds.value.filter(r => {
    const ds = extractDateStr(r);
    if (!ds) return false; // 没有日期则视为不匹配（若想包含，改成 true）
    const t = new Date(`${ds}T12:00:00`).getTime(); // 中午避免 DST 边界
    return t >= start.getTime() && t <= end.getTime();
  });
  empty.value = reminds.value.length === 0;
}

// 加载重复类型字典
const loadRepeatDict = async () => {
  try {
    const res = await getDictData('reminders_repeat_type')
    const arr = Array.isArray(res?.data) ? res.data : (Array.isArray(res) ? res : [])
    const map = {}
    arr.forEach(item => {
      const val = item?.dictValue ?? item?.value ?? item?.code ?? item?.key
      const label = item?.dictLabel ?? item?.label ?? item?.text ?? item?.name ?? val
      if (val !== undefined && val !== null) map[String(val)] = label
    })
    repeatTypeMap.value = map
  } catch (e) {
    repeatTypeMap.value = {}
  }
}

const getRepeatLabel = (remind) => {
  const code = remind?.repeatType
  if (code === undefined || code === null || code === '') return ''
  return repeatTypeMap.value[String(code)] || ''
}

const onSearch = () => {
  // 后端暂不支持，直接本地过滤
  applyFilter();
}
const onReset = () => {
  search.value.range = [];
  applyFilter();
}
const onEditRemind = (idx) => {
  // 获取当前提醒信息
  const remind = reminds.value[idx];
  // 跳转到提醒编辑页面，并传递参数
  reminderEditStore.set({
    id: remind.id,
    title: remind.title,
    time: remind.time,
    repeatType: remind.repeatType,
    nextTrigger: remind.nextTrigger,
    baseDate: remind.baseDate,
    description: remind.description
  })
  go('/pages/pc/remindEdit');
  /* 原 query 结构保留注释
    {
  // 后端字段
  id: remind.id,
  title: remind.title,
  time: remind.time,
  repeatType: remind.repeatType,
  nextTrigger: remind.nextTrigger,
  baseDate: remind.baseDate,
  // 兼容旧字段名（如果编辑页沿用旧参数）
  content: remind.title,
  repeat: remind.repeatType,
  date: remind.nextTrigger || remind.baseDate
    }
  */
};
const onDeleteRemind = async (idx) => {
  // 获取当前提醒信息
  const remind = reminds.value[idx];
  if (!remind || !remind.id) {
	uni.showToast({ title: '当前数据缺少ID，无法删除', icon: 'none' });
    return;
  }

  try {
    // 显示确认对话框
    await ElMessageBox.confirm(
      `确定要删除提醒"${remind.title || '未命名提醒'}"吗？删除后无法恢复。`,
      '确认删除',
      {
        confirmButtonText: '确定删除',
        cancelButtonText: '取消',
        type: 'warning',
        confirmButtonClass: 'el-button--danger'
      }
    );

    // 调用删除接口
    const response = await deleteReminder(remind.id);
    
    if (response.code === 200) {
	  uni.showToast({ title: '提醒删除成功', icon: 'success' });
      // 从当前显示列表中移除
      reminds.value.splice(idx, 1);
      // 从原始数据中也移除
      const originalIndex = originalReminds.value.findIndex(r => r.id === remind.id);
      if (originalIndex !== -1) {
        originalReminds.value.splice(originalIndex, 1);
      }
      // 更新空状态
      empty.value = reminds.value.length === 0;
      // 更新总数
      total.value = Math.max(0, total.value - 1);
    } else {
	  uni.showToast({ title: response.msg || "删除失败", icon: 'success' });
    }
  } catch (error) {
    if (error === 'cancel') {
      // 用户取消删除
      return;
    }
    console.error('删除提醒失败:', error);
    uni.showToast({ title: "删除失败，请重试", icon: 'success' });
  }
};
const onAddRemind = () => {
  // 跳转到提醒新增页面
  reminderEditStore.clear();
  go('/pages/pc/remindEdit');
};
const goBack = () => {
  go('/pages/pc/index', { replace: false });
};

onMounted(() => {
  // 并行加载字典与列表
  loadRepeatDict()
  fetchList(true)
})
</script>

<style scoped>
/* 时间检索区域样式 */
.remind-search-row {
  display: flex;
  align-items: center;
  padding: 18px 16px 0 32px; /* 增加右侧内边距 */
  background: #f7f8fa;
}
.remind-search-box {
  display: flex;
  align-items: center;
  background: #fff;
  border-radius: 8px;
  border: 1px solid #dcdfe6;
  box-shadow: none;
  padding: 0 8px 0 12px;
  min-width: 0;        /* 允许收缩 */
  /* 跟随内容变宽：fit-content，并限制不超过行可用宽度 */
  width: -moz-fit-content;
  width: fit-content;
  max-width: calc(100% - 48px);
  height: 44px;
}
.remind-search-btn-box {
  flex-shrink: 0;
}
.remind-search-calendar {
  font-size: 22px;
  color: #bfcad7;
  margin-right: 8px;
}
.remind-search-to {
  margin: 0 8px;
  color: #888;
  font-size: 16px;
  font-weight: 700;
}
.remind-search-box .el-date-editor {
  background: transparent;
  border: none;
  box-shadow: none;
  /* 默认在正常屏宽下维持原大小（给非 scoped 深度兜底）*/
  flex: 0 0 280px;
  width: 280px;
  margin-right: 8px;   /* 和按钮间距 */
}
/* 深度选择器，确保在 scoped 下也能命中 Element Plus 内部结构 */
.remind-search-box :deep(.el-date-editor),
.remind-search-box :deep(.el-range-editor) {
  flex: 0 0 280px;
  width: 280px;
  margin-left: 12px;   /* 还原之前的左间距 */
  margin-right: 8px;
}
.remind-search-box .el-input__wrapper {
  background: #fff;
  border: 1px solid #dcdfe6;
  box-shadow: none;
  font-size: 14px;
  height: 32px;
  border-radius: 6px;
  margin-right: 8px;
}
.remind-search-box .el-input__inner {
  color: #888;
  font-size: 14px;
  font-weight: 500;
}
.remind-search-box .el-button {
  margin-left: 8px;
  height: 32px;
  font-size: 14px;
  border-radius: 6px;
  box-shadow: none;
}
.remind-search-btn {
  background: #409eff;
  border-color: #409eff;
  color: #fff;
}
.remind-search-btn:hover { filter: brightness(0.95); }
.remind-reset-btn {
  background: #fff;
  color: #606266;
  border: 1px solid #dcdfe6;
}
.remind-reset-btn:hover { background: #f5f7fa; }
.remind-search-box :deep(.el-input__wrapper.is-focus),
.remind-search-box :deep(.is-focus .el-input__wrapper),
.remind-search-box :deep(.el-range-editor.is-active),
.remind-search-box :deep(.el-range-editor.is-active .el-input__wrapper) {
  border-color: #409eff !important;
  box-shadow: 0 0 0 2px rgba(64,158,255,0.15) !important;
}
.layout-container {
  display: flex;
  height: 100vh;
  background-color: #1976ed;
  border-radius: 0;
  overflow: hidden;
  position: relative;
  align-items: stretch;
}
.main-content.main-content-rounded {
  flex: 1;
  display: flex;
  flex-direction: column;
  background: #fff;
  border-radius: 24px 0 0 24px;
  overflow: hidden;
}
.remind-title-row {
  display: flex;
  align-items: center;
  /* margin-bottom: 24px; */
}
.main-header {
  height: 64px;
  display: flex;
  align-items: center;
  padding-left: 24px;
  background: #fff;
  font-size: 20px;
  font-weight: 600;
  border-bottom: none;
  flex-shrink: 0;
}
.back-btn {
  font-size: 32px;
  color: #222;
  cursor: pointer;
  margin-right: 18px;
  font-weight: 700;
}
.remind-title {
  font-size: 32px;
  font-weight: 700;
  color: #222;
}
.main-divider {
  height: 1px;
  background: #e3e7ed;
  margin: 0 -32px 0 -32px;
}
.remind-card-list {
  background: #f7f8fa;
  padding: 32px 10px 0 32px;
  flex: 1;
  display: flex;
  align-content: flex-start;
  gap: 40px 40px;
  flex-direction: column;
  overflow-y: auto;
  min-height: 0;
}
.remind-card-list.is-empty .el-row {
  display: flex;
  justify-content: flex-start; /* 与列表保持一致的左对齐 */
}
.remind-card-list.is-empty .el-col {
  flex: 0 0 auto; /* 不受 25% 栅格限制，按卡片自身宽度显示 */
  max-width: none;
}
.remind-card-list.is-empty {
  display: flex;
  flex-direction: column; /* 空态：上下堆叠 */
  align-items: center;     /* 水平居中 */
  justify-content: center; /* 垂直居中 */
  padding: 0;              /* 去掉上左内边距，确保真正居中 */
}
.remind-card-list.is-empty .empty-tip {
  width: 100%;
  text-align: center;
  margin: 0;
  font-size: 30px; /* 提高字号 */
  color: #666;
}
.loading-tip { color:#888; font-size:14px; margin: 0 0 16px 8px; }
.empty-tip { color:#888; font-size:14px; margin: 0 0 16px 8px; }
.empty-link { color:#1976ed; cursor:pointer; }
.empty-link:hover { text-decoration: underline; }
.el-row {
  flex-wrap: wrap !important;
  align-content: flex-start;
}
.el-col {
  flex: 0 0 25%;
  max-width: 25%;
  box-sizing: border-box;
  display: flex;
  align-items: stretch;
}
@media (max-width: 1200px) {
  .el-col {
    flex: 0 0 50%;
    max-width: 50%;
  }
}
@media (max-width: 900px) {
  /* 小屏保底占满可用宽度，避免被裁切 */
  .remind-search-box {
    width: 100%;
    max-width: 100%;
  }
  .el-col {
    flex: 0 0 50%;
    max-width: 50%;
  }
  /* 小屏下允许日期选择器自适应缩小 */
  .remind-search-box .el-date-editor {
    flex: 1 1 auto;
    width: auto;
    min-width: 220px;
  }
  .remind-search-box :deep(.el-date-editor),
  .remind-search-box :deep(.el-range-editor) {
    flex: 1 1 auto;
    width: auto;
    min-width: 220px;
  }
  .remind-card-list .el-col {
    flex: 0 0 100%;
    max-width: 100%;
  }
  .remind-info-card {
    width: 90%;
    height: auto;
  }
  .remind-info-content {
    align-items: flex-start;
    min-height: unset;
  }
}
@media (max-width: 600px) {
  .remind-search-box {
	flex-direction: column;
	height: auto;
	padding: 12px 0;
  }
  .remind-search-btn-box {
	  display: flex;
	  gap: 30px;
	  margin-top: 8px;
	  margin-right: 8px;
  }
  .el-col {
    flex: 0 0 100%;
    max-width: 100%;
  }
}
.remind-info-card {
  width: 100%;
  height: 150px;
  background: #fff;
  border-radius: 16px;
  box-shadow: 0 2px 16px #e3e7ed;
  display: flex;
  flex-direction: column;
  padding: 32px 0 10px 0;
  position: relative;
  margin-bottom: 20px;  
}
.remind-info-content {
  display: flex;
  flex-direction: row;
  align-items: center;
  justify-content: flex-start;
  /* 让该区域和右侧徽标同处一行，给徽标留出空间 */
  flex: 1 1 auto;
  min-width: 0;
  width: auto;
  margin-bottom: 12px;
  position: relative;
}
.remind-info-content-wrap {
  position: relative;
  width: 100%;
  min-height: 72px;
  display: flex;
  align-items: flex-start; /* 顶端对齐，徽标靠上 */
  justify-content: space-between; /* 内容在左，徽标在右 */
  gap: 12px;
}
.remind-info-repeat-badge {
  /* 参与正常文档流，位于右侧，不再覆盖标题 */
  position: static;
  flex: 0 0 auto;
  font-size: 16px;
  font-weight: 700;
  color: #409eff;
  background: #fff;
  padding: 0 8px;
  border-radius: 6px;
  box-shadow: 0 0 4px rgba(0,0,0,0.03);
  line-height: 1.8;
  white-space: nowrap;
  max-width: 48%;
  overflow: hidden;
  text-overflow: ellipsis;
}
.remind-info-main {
  display: flex;
  flex-direction: column;
  justify-content: center;
  /* 占据剩余空间，允许内容收缩并出现省略 */
  flex: 1 1 auto;
  min-width: 0;
}
.remind-info-title {
  font-size: 30px;
  font-weight: 700;
  color: #222;
  margin-bottom: 6px;
  /* 单行省略，避免与右侧徽标重叠 */
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  background: #fff;
  padding-right: 8px;
}
.remind-info-time {
  font-size: 15px;
  color: #409eff;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  background: #fff;
  padding-right: 8px;
}
.remind-info-repeat {
  font-size: 14px;
  color: #888;
  background: #fff;
  padding-right: 8px;
  position: relative;
}
.remind-info-actions {
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 0;
  border-top: 1px solid #e3e7ed;
  padding-top: 10px;
  margin-top: 10px;
}
.remind-info-action-btn {
  flex: 1;
  text-align: center;
  border: none;
  background: none;
  font-size: 16px;
  color: #1976ed;
  padding: 0;
}
.remind-info-action-btn.delete {
  color: #ff3b30;
}
.remind-info-action-btn:focus,
.remind-info-action-btn:focus-visible,
.remind-info-action-btn:active {
  outline: none !important;
  box-shadow: none !important;
  border-color: transparent !important;
}
/* 若仍出现蓝色描边（某些浏览器默认 focus ring），可进一步针对原生 button 覆盖 */
.remind-info-actions :deep(button:focus),
.remind-info-actions :deep(button:focus-visible) {
  outline: none !important;
  box-shadow: none !important;
}
.remind-info-action-divider {
  width: 1px;
  height: 35px;
  background: #e3e7ed;
  margin: 0 12px;
}
.remind-info-add-card {
  border: 1px solid #e3e7ed;
  background: #fff;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 16px;
  box-shadow: 0 2px 16px #e3e7ed;
  width: 100%;
  height: 160px;
  flex-direction: column;
  padding: 24px 0 8px 0;
  margin-bottom: 8px;
}
.remind-info-add {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100%;
}
.remind-info-add-icon {
  font-size: 32px;
  color: #222;
  margin-bottom: 8px;
}
.remind-info-add-text {
  font-size: 18px;
  color: #888;
  margin-top: 12px;
}
@media (max-width: 900px) {
  .remind-card-list .el-col {
    flex: 0 0 100%;
    max-width: 100%;
  }
  .remind-info-card {
    width: 90%;
    height: auto;
  }
  .remind-info-content {
    align-items: flex-start;
    min-height: unset;
  }
}
</style>
